package com.elock.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.entity.PcMenu;

/**
 * Dao - PC菜单
 * @author 仁德
 */
@Repository("pcMenuBaseDao")
public class PcMenuBaseDao extends DaoCenter {

	/**
	 * 根据用户和企业查找菜单
	 * 
	 * @param memberId
	 * @param companyInfoId
	 * @return
	 */
	public List<PcMenu> findMenuList(String storeMemberId, Long companyInfoId,
			Integer type) {

		if (ConvertUtil.isEmpty(storeMemberId)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		List<Object> list = new ArrayList<Object>();

		StringBuilder sql = new StringBuilder();
		sql.append(
				"select distinct m.*");
		sql.append(
				" from pc_menu m, pc_menu_role mr, pc_role r, pc_user_role ur");
		sql.append(
				" where m.id = mr.pc_menus and mr.pc_roles = r.id and r.id = ur.pc_role and ur.member = ?");

		list.add(storeMemberId);
		if (type != null) {
			sql.append(" and m.type = ?");
			list.add(type);
		}
		sql.append(" order by m.orders");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		List<PcMenu> menus = getNativeDao().findListManaged(sql.toString(),
				objs,
				0,
				PcMenu.class);

		return menus;
	}

	public Integer findMenuCount(String storeMemberId, Long companyInfoId,
			Integer type, String code) {

		if (ConvertUtil.isEmpty(storeMemberId)) {
			ExceptionUtil.throwDaoException("value is empty!");
		}
		List<Object> list = new ArrayList<Object>();

		StringBuilder sql = new StringBuilder();
		sql.append("select count(m.id)");
		sql.append(
				" from pc_menu m, pc_menu_role mr, pc_role r, pc_user_role ur");
		sql.append(
				" where m.id = mr.pc_menus and mr.pc_roles = r.id and r.id = ur.pc_role and ur.member = ? and m.menu_code = ?");

		list.add(storeMemberId);
		list.add(code);
		if (type != null) {
			sql.append(" and m.type = ?");
			list.add(type);
		}
		sql.append(" order by m.orders");

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		Integer count = getNativeDao().findInt(sql.toString(), objs);

		return count;
	}
}